package com.framework2.util;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.WindowManager;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.asiainfo.iov.activity.BaseActivity;
import com.asiainfo.iov.configs.ConstantsME;
import com.asiainfo.iov.configs.EventBusTag;
import com.asiainfo.iov.configs.InterfaceConfig;
import com.asiainfo.iov.networkModel.HttpUtil;
import com.asiainfo.iov.wchatutil.JsonUtils;
import com.asiainfo.iov.wxapi.WXEntryActivity;
import com.framework.security.RSAmethodInAssets;
import com.framework.utils.KeyBoardUtil;
import com.framework.utils.PreferencesHelper;
import com.framework.utils.ToastUtil;
import com.framework.utils.Y;
import com.framework2.popupwindow.BindingPhonePopupwindow;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.yaxin.yyt.R;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

/**
 * 三方授权登录util
 *
 * @author YobertJomi
 * className ThirdLoginUtil
 * created at  2017/4/25  13:59
 */
public class ThirdWchatLoginUtil {
    private static volatile ThirdWchatLoginUtil singleton;
    private final String WCHAT_APP_ID = "wxf159411fd8b11d79";// 微信开放平台申请到的app_id
    private final String WCHAT_APP_SECRET = "ac9a8bbaa1684cf81952f190f6b26463";// 微信开放平台申请到的app_id对应的app_secret
    private final int RETURN_OPENID_ACCESSTOKEN = 0;// 返回openid，accessToken消息码
    private final int RETURN_NICKNAME_UID = 1; // 返回昵称，uid消息码
    private final String WEIXIN_SCOPE = "snsapi_userinfo";// 用于请求用户信息的作用域
    private final String WEIXIN_STATE = "android_wchat_login_state"; // 自定义
    //*************************************************************************************//chat_Login
    ////////////////////////微信登录
    private IWXAPI api;
    private String wchatOpenId;
    private String wChatImgUrl;
    private String wChatNick;
    private Context context;
    private String phoneTemp;
    private String pwdTemp;
    private String captchaTemp;
    private int thirdType = 3;//2qq  3wchat
    private MyCountDownTimer myCountDownTimer;
    private String verifyKey;//验证码key
    /////////////////微信登录
    // *************************************************************************************//wchat_Login
    /////////////////微信登录
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Y.y("微信登录：" + "handler:" + "丫丫");
            switch (msg.what) {
                case RETURN_OPENID_ACCESSTOKEN:
                    Y.y("微信登录：" + "handler:" + "RETURN_OPENID_ACCESSTOKEN");
                    Bundle bundle1 = (Bundle) msg.obj;
                    String accessToken = bundle1.getString("access_token");
                    String openId = bundle1.getString("openid");
                    Y.y("微信登录：" + "accessToken:" + accessToken);
                    Y.y("微信登录：" + "openId:" + openId);
                    getUID(openId, accessToken);
                    break;

                case RETURN_NICKNAME_UID:
                    Y.y("微信登录：" + "handler:" + "RETURN_NICKNAME_UID");
                    Bundle bundle2 = (Bundle) msg.obj;
                    String nickname = bundle2.getString("nickname");
                    String headimgurl = bundle2.getString("headimgurl");
                    String unionid = bundle2.getString("unionid");
                    String openId2 = bundle2.getString("openId");
                    Y.y("微信登录：" + "unionid:" + unionid);
                    Y.y("微信登录：" + "openId:" + openId2);
                    Y.y("微信登录：" + "headimgurl:" + headimgurl);
                    Y.y("微信登录：" + "nickname:" + nickname);
                    wchatOpenId = openId2;
                    wChatImgUrl = headimgurl;
                    wChatNick = nickname;
//                    requestThirdLoginBindPhone(1, RSAmethod.rsaDecrypt(context, PreferencesHelper.getInstance()
// .getStringData(ConstantsME.PHONE)), wchatOpenId, wChatImgUrl, wChatNick);
                    requestThirdLoginCheckBinding(context, thirdType, wchatOpenId, wChatImgUrl, wChatNick);
                    break;

                default:
                    break;
            }
        }
    };

    private ThirdWchatLoginUtil() {
    }

    public static ThirdWchatLoginUtil getInstance() {
        if (singleton == null) {
            synchronized (ThirdWchatLoginUtil.class) {
                if (singleton == null) {
                    singleton = new ThirdWchatLoginUtil();
                }
            }
        }
        return singleton;
    }

    //////////////////////微信登录
    public void wchatLogin(Context context) {
        if (!TextUtils.isEmpty(wchatOpenId) && !TextUtils.isEmpty(wChatImgUrl) && !TextUtils.isEmpty(wChatNick)) {
//            CustomProgressDialogUtils.showProcessDialog(context, "关联手机号");
//            requestThirdLoginBindPhone(1, RSAmethod.rsaDecrypt(context, PreferencesHelper.getInstance()
// .getStringData(ConstantsME.PHONE)),
//                    wchatOpenId, wChatImgUrl, wChatNick);
//            showBindingPop(context, thirdType, RSAmethod.rsaEncrypt(context, PreferencesHelper.getInstance()
// .getStringData(ConstantsME.PHONE)), wchatOpenId, pwdTemp, captchaTemp);
            requestThirdLoginCheckBinding(context, thirdType, wchatOpenId, wChatImgUrl, wChatNick);
        } else {
            this.context = context;
            if (null == api) {
                api = WXAPIFactory.createWXAPI(context, WCHAT_APP_ID, true);
                api.registerApp(WCHAT_APP_ID);
            }
            try {
                api.handleIntent(((BaseActivity) context).getIntent(), new WXEntryActivity());
            } catch (Exception e) {
                e.printStackTrace();
            }
            CustomLoadingDialogUtils.showProcessDialog(context, "跳转到微信");
            final SendAuth.Req req = new SendAuth.Req();
            req.scope = WEIXIN_SCOPE;
            req.state = WEIXIN_STATE;
            api.sendReq(req);
        }
    }

    /**
     * 获取openid accessToken值用于后期操作
     *
     * @param code 请求码
     */
    public void getResult(final String code) {
        CustomLoadingDialogUtils.showProcessDialog(context, "正在绑定");
        Y.y("微信登录：" + "getResult:" + code);
        new Thread() {// 开启工作线程进行网络请求
            public void run() {
                String path = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="
                        + WCHAT_APP_ID
                        + "&secret="
                        + WCHAT_APP_SECRET
                        + "&code="
                        + code
                        + "&grant_type=authorization_code";
                try {
                    JSONObject jsonObject = JsonUtils
                            .initSSLWithHttpClinet(path);// 请求https连接并得到json结果
                    if (null != jsonObject) {
                        String openid = jsonObject.getString("openid").toString().trim();
                        String access_token = jsonObject.getString("access_token").toString().trim();
                        Y.y("微信openid = " + openid);
                        Y.y("微信access_token = " + access_token);

                        Message msg = handler.obtainMessage();
                        msg.what = RETURN_OPENID_ACCESSTOKEN;
                        Bundle bundle = new Bundle();
                        bundle.putString("openid", openid);
                        bundle.putString("access_token", access_token);
                        msg.obj = bundle;
                        handler.sendMessage(msg);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                return;
            }
        }.start();
    }

    /**
     * 获取用户唯一标识
     *
     * @param openId
     * @param accessToken
     */
    private void getUID(final String openId, final String accessToken) {
        Y.y("微信登录：" + "getUID:" + openId + "      " + accessToken);
        new Thread() {
            @Override
            public void run() {
                String path = "https://api.weixin.qq.com/sns/userinfo?access_token="
                        + accessToken + "&openid=" + openId;
                JSONObject jsonObject = null;
                try {
                    jsonObject = JsonUtils.initSSLWithHttpClinet(path);
                    String nickname = jsonObject.getString("nickname");
                    String unionid = jsonObject.getString("unionid");
                    String headimgurl = jsonObject.getString("headimgurl");
                    Y.y("微信jsonObject = " + jsonObject);
                    Y.y("微信nickname = " + nickname);
                    Y.y("微信unionid = " + unionid);
                    Y.y("headimgurl = " + headimgurl);

                    Message msg = handler.obtainMessage();
                    msg.what = RETURN_NICKNAME_UID;
                    Bundle bundle = new Bundle();
                    bundle.putString("nickname", nickname);
                    bundle.putString("headimgurl", headimgurl);
                    bundle.putString("unionid", unionid);
                    bundle.putString("openId", openId);
                    msg.obj = bundle;
                    handler.sendMessage(msg);
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    /**
     * 请求 检测三方登录是否绑定phone
     */
    private void requestThirdLoginCheckBinding(final Context context, final int type, final String openId, final
    String imgUrl, final String nick) {
        HttpUtil.getInstance().requestThirdLoginCheckBinding(InterfaceConfig.thirdLoginCheckBinding, type, openId,
                nick, imgUrl,
                new HttpUtil.OnRequestResult<String>() {
                    @Override
                    public void onSuccess(String... s) {
                        CustomLoadingDialogUtils.dismissProcessDialog();
                        if (null != s) {
                            if (!TextUtils.isEmpty(s[0])) {
                                PreferencesHelper.getInstance().putInfo(ConstantsME.PHONE, RSAmethodInAssets.rsaEncrypt
                                        (context, s[0]));
                            }
                            PreferencesHelper.getInstance().putInfo(ConstantsME.token, s.length > 1 ? s[1] : "");
                            PreferencesHelper.getInstance().putInfo(ConstantsME.nick, s.length > 2 ? s[2] : "");
                            PreferencesHelper.getInstance().putInfo(ConstantsME.imgUrl, s.length > 3 ? s[3] : "");
                            PreferencesHelper.getInstance().putInfo(ConstantsME.LOGINED, true);
                            showBindingPop(context, thirdType, RSAmethodInAssets.rsaDecrypt(context, PreferencesHelper
                                    .getInstance().getStringData(ConstantsME.PHONE)), wchatOpenId, pwdTemp,
                                    captchaTemp);
                        } else {
                            showBindingPop(context, thirdType, RSAmethodInAssets.rsaDecrypt(context, PreferencesHelper
                                    .getInstance().getStringData(ConstantsME.PHONE)), wchatOpenId, pwdTemp,
                                    captchaTemp);
                        }
                    }

                    @Override
                    public void onFail(int code, String msg) {
                        CustomLoadingDialogUtils.dismissProcessDialog();
                        ToastUtil.getInstance().showToast(TextUtils.isEmpty(msg) ? "未检测是否绑定手机" : msg);
//                        showBindingPop(context,type, "", openId, "", "");
                        showBindingPop(context, thirdType, RSAmethodInAssets.rsaDecrypt(context, PreferencesHelper
                                .getInstance().getStringData(ConstantsME.PHONE)), wchatOpenId, pwdTemp, captchaTemp);
                    }
                });
    }

    /**
     * 请求 三方登录绑定phone
     */
    private void requestThirdLoginBindPhone(final int type, final String openId, final String phone, final String
            mobileValidVoucher, final String moblieVerifyCode, final String password) {
        HttpUtil.getInstance().requestThirdLoginBindPhone(InterfaceConfig.thirdLoginBindPhone, type, openId, phone,
                mobileValidVoucher, moblieVerifyCode, password,
                new HttpUtil.OnRequestResult<String>() {
                    @Override
                    public void onSuccess(String... s) {
                        CustomLoadingDialogUtils.dismissProcessDialog();
                        if (null != s) {
                            if (!TextUtils.isEmpty(s[0]) && TextUtils.equals("true", s[0])) {
                                PreferencesHelper.getInstance().putInfo(ConstantsME.PHONE, RSAmethodInAssets.rsaEncrypt
                                        (context, phone));
                                if (s.length > 1 && !TextUtils.isEmpty(s[1]))
                                    PreferencesHelper.getInstance().putInfo(ConstantsME.token, s[1]);
                                if (s.length > 2 && !TextUtils.isEmpty(s[2]))
                                    PreferencesHelper.getInstance().putInfo(ConstantsME.nick, s[2]);
                                if (s.length > 3 && !TextUtils.isEmpty(s[3]))
                                    PreferencesHelper.getInstance().putInfo(ConstantsME.imgUrl, s[3]);
                                PreferencesHelper.getInstance().putInfo(ConstantsME.LOGINED, true);
                                if (type == 2) {
                                    PreferencesHelper.getInstance().putInfo(ConstantsME.qqBind, true);
                                    EventBus.getDefault().post("success", EventBusTag.thirdBindingQQ);
                                } else if (type == 3) {
                                    PreferencesHelper.getInstance().putInfo(ConstantsME.wChatBind, true);
                                    EventBus.getDefault().post("success", EventBusTag.thirdBinding);
                                }
                            } else {
                                onFail(1, "");
                            }
                        }
                    }

                    @Override
                    public void onFail(int code, String msg) {
                        ToastUtil.getInstance().showToast(TextUtils.isEmpty(msg) ? "绑定失败" : msg);
                        CustomLoadingDialogUtils.dismissProcessDialog();
                        showBindingPop(context, type, phone, openId, password, moblieVerifyCode);
                    }
                });
    }

    private void showBindingPop(final Context context, final int type, String phone, final String openId, final
    String pwd, final String captcha) {
        CustomLoadingDialogUtils.dismissProcessDialog();
        ((Activity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED |
                WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        final BindingPhonePopupwindow pop = new BindingPhonePopupwindow(context);
        long last = PreferencesHelper.getInstance().getLongData(ConstantsME.captcha_last_clicked);
        long currentTimeMillis = System.currentTimeMillis();
        long difference = currentTimeMillis - last;
        int diff = (int) ((60 * 1000 - difference) / 1000);
        if (difference < 60 * 1000 && diff >= 1) {
            new MyCountDownTimer(context, pop.getCaptcaTextView(), diff * 1000, 1000).start();
        }
        pop.setContent(phone).setPassword(pwd).setCaptcha(captcha).setOnGetCaptchaListener(new BindingPhonePopupwindow.OnGetCaptchaListener() {
            @Override
            public void onGetCaptchaListener(String phoneNum) {
                myCountDownTimer = new MyCountDownTimer(context, pop.getCaptcaTextView(), 60000, 1000);
                myCountDownTimer.start();
                PreferencesHelper.getInstance().putInfo(ConstantsME.captcha_last_clicked, System.currentTimeMillis());
                CustomLoadingDialogUtils.showProcessDialog(context, "获取验证码");
                requestCaptcha(context, pop.getCaptcaTextView(), phoneNum);
            }
        });
        pop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                ((Activity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN |
                        WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
            }
        });
        pop.setOnSureClickListener(new BindingPhonePopupwindow.OnSureClickListener() {
            @Override
            public void onSureClickListener(String phone, String pwd, String captcha) {
                phoneTemp = phone;
                pwdTemp = pwd;
                captchaTemp = captcha;
                if (TextUtils.isEmpty(verifyKey)) {
                    ToastUtil.getInstance().showToast("请先获取验证码");
                } else {
                    CustomLoadingDialogUtils.showProcessDialog(context, "正在绑定微信号");
                    KeyBoardUtil.getInstance().isCloseSoftInputMethod(context, pop.getEditText(), true);
                    requestThirdLoginBindPhone(type, openId, phone, verifyKey, captcha, pwd);
                    pop.dismiss();
                }
            }
        }).showAtLocation(((Activity) context).getWindow().getDecorView(), Gravity.CENTER, 0, 0);
    }

    /**
     * 请求获取验证码
     */
    private void requestCaptcha(final Context context, final TextView tv_captcha, String phone) {
        HttpUtil.getInstance().requestMobileVerify(InterfaceConfig.captcha, 4, phone,
                new HttpUtil.OnRequestResult<String>() {
                    @Override
                    public void onSuccess(String... s) {
                        CustomLoadingDialogUtils.dismissProcessDialog();
                        ToastUtil.getInstance().showToast("获取验证码成功");
                        if (null != s && !TextUtils.isEmpty(s[0])) {
                            verifyKey = s[0];
                        }
                    }

                    @Override
                    public void onFail(int code, String msg) {
                        CustomLoadingDialogUtils.dismissProcessDialog();
                        ToastUtil.getInstance().showToast(TextUtils.isEmpty(msg) ? "获取验证码失败" : msg);
                        PreferencesHelper.getInstance().putInfo(ConstantsME.captcha_last_clicked, 0L);
                        if (null != myCountDownTimer)
                            myCountDownTimer.cancel();
                        tv_captcha.setText("重新获取");
                        tv_captcha.setTextColor(context.getResources().getColor(R.color._blue));
                        tv_captcha.setClickable(true);
                    }
                });
    }

    public void destroy() {
        if (singleton != null) {
            singleton = null;
        }
        if (context != null) {
            context = null;
        }
        if (api != null) {
            api = null;
        }
        if (myCountDownTimer != null) {
            myCountDownTimer.cancel();
            myCountDownTimer = null;
        }
    }

    private class MyCountDownTimer extends CountDownTimer {
        private TextView tv_captcha;

        public MyCountDownTimer(Context context, TextView tv_captcha, long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);// 参数依次为总时长,和计时的时间间隔
            this.tv_captcha = tv_captcha;
        }

        @Override
        public void onFinish() {// 计时完毕时触发
            tv_captcha.setText("重新获取");
            tv_captcha.setTextColor(context.getResources().getColor(R.color._blue));
            tv_captcha.setClickable(true);
        }

        @Override
        public void onTick(long millisUntilFinished) {// 计时过程显示
            try {
                tv_captcha.setClickable(false);
                tv_captcha.setTextColor(context.getResources().getColor(
                        R.color.trans));
                tv_captcha.setText(millisUntilFinished / 1000 + "秒");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
